package com.sunrise.gateway.web.core;

import com.dap.utils.DateUtil;
import com.sunrise.gateway.commons.watermark.WatermarkUtils;
import com.sunrise.gateway.commons.watermark.WatermarkResult;
import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

@Service
public class ImageOSSEngine extends OSSEngineBase {
    public ImageOSSEngine() {
        super();
    }

    private static String getFileSuffixFromFileName(String fileName) {
        int dotIdx = fileName.indexOf('.');
        if (dotIdx < 0 || dotIdx == fileName.length() - 1) {
            return "jpg";
        } else {
            return fileName.substring(dotIdx + 1);
        }
    }

    @Override
    protected String handleFileItem(HttpServletRequest request, FileItem item) throws Exception {
        String fileNamePrefix = DateUtil.format(new Date(), "yyyyMMdd") + "/" + UUID.randomUUID();
        String fileNameSuffix = getFileSuffixFromFileName(item.getName());

        InputStream input = item.getInputStream();
        long length = item.getSize();

        String watermarkParam = request.getParameter("watermarkParam");
        if (!StringUtils.isEmpty(watermarkParam)) {
            WatermarkResult watermarkResult = WatermarkUtils.parseAndPrintWatermark(input, watermarkParam);
            if (null != watermarkResult) {
                input.close();

                input = new ByteArrayInputStream(watermarkResult.dataBytes);
                length = watermarkResult.dataBytes.length;
                fileNameSuffix = watermarkResult.imageFormat;
            }
        }

        String fileName = fileNamePrefix + "." + fileNameSuffix;
        uploadService.putObject(ossConfig.getBucket(), fileName, input, length);
        input.close();

        return ossConfig.resolveFullUrl(fileName);
    }

}
